<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 导航栏 -->
    <nav class="bg-white shadow">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex items-center">
            <router-link to="/" class="text-xl font-bold text-gray-900">
              {{ $t('app.title') }}
            </router-link>
          </div>

          <div class="flex items-center space-x-4">
            <router-link
              to="/posts"
              class="text-gray-700 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium"
            >
              {{ $t('nav.backToList') }}
            </router-link>
          </div>
        </div>
      </div>
    </nav>

    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 加载状态 -->
      <div v-if="loading" class="flex justify-center py-12">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
      </div>

      <!-- 帖子详情 -->
      <div v-else-if="post" class="space-y-8">
        <!-- 帖子状态 -->
        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex items-center justify-between">
            <div>
              <h1 class="text-2xl font-bold text-gray-900">
                {{ $t('post.searchingFor', { name: post.pet?.name }) }}
              </h1>
              <p class="mt-1 text-gray-600">
                {{ $t('post.publishedAt', { date: formatDate(post.created_at) }) }}
              </p>
            </div>
            <span
              :class="[
                'px-3 py-1 text-sm font-medium rounded-full',
                post.post_status === 'searching'
                  ? 'bg-yellow-100 text-yellow-800'
                  : post.post_status === 'found'
                  ? 'bg-green-100 text-green-800'
                  : 'bg-gray-100 text-gray-800'
              ]"
            >
              {{ $t(POST_STATUS_LABELS[post.post_status]) }}
            </span>
          </div>
        </div>

        <!-- 宠物信息 -->
        <div class="bg-white rounded-lg shadow p-6">
          <h2 class="text-lg font-medium text-gray-900 mb-4">{{ $t('post.petInfo') }}</h2>

          <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- 宠物照片 -->
            <div class="flex justify-center">
              <img
                v-if="post.pet?.photo_url"
                :src="getFullImageUrl(post.pet.photo_url)"
                :alt="post.pet.name"
                class="max-w-full max-h-96 object-contain rounded-lg shadow-md cursor-pointer"
                @click="showImageModal = true"
              />
              <div
                v-else
                class="w-full h-64 bg-gray-200 rounded-lg flex items-center justify-center"
              >
                <svg class="w-16 h-16 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                </svg>
              </div>
            </div>

            <!-- 宠物详细信息 -->
            <div class="space-y-4">
              <div class="grid grid-cols-2 gap-4">
                <div>
                  <dt class="text-sm font-medium text-gray-500">{{ $t('post.fields.petName') }}</dt>
                  <dd class="mt-1 text-sm text-gray-900">{{ post.pet?.name }}</dd>
                </div>
                <div>
                  <dt class="text-sm font-medium text-gray-500">{{ $t('post.fields.petSpecies') }}</dt>
                  <dd class="mt-1 text-sm text-gray-900">{{ post.pet?.species }}</dd>
                </div>
                <div>
                  <dt class="text-sm font-medium text-gray-500">{{ $t('post.fields.petColor') }}</dt>
                  <dd class="mt-1 text-sm text-gray-900">{{ post.pet?.color }}</dd>
                </div>
                <div>
                  <dt class="text-sm font-medium text-gray-500">{{ $t('post.fields.petGender') }}</dt>
                  <dd class="mt-1 text-sm text-gray-900">
                    {{ getGenderLabel(post?.pet?.gender) }}
                  </dd>
                </div>
                <div v-if="post.pet?.breed">
                  <dt class="text-sm font-medium text-gray-500">{{ $t('post.fields.petBreed') }}</dt>
                  <dd class="mt-1 text-sm text-gray-900">{{ post.pet.breed }}</dd>
                </div>
                <div v-if="post.pet?.age">
                  <dt class="text-sm font-medium text-gray-500">{{ $t('post.fields.petAge') }}</dt>
                  <dd class="mt-1 text-sm text-gray-900">{{ $t('post.ageYears', { age: post.pet.age }) }}</dd>
                </div>
              </div>

              <div v-if="post.pet?.description">
                <dt class="text-sm font-medium text-gray-500">{{ $t('post.fields.description') }}</dt>
                <dd class="mt-1 text-sm text-gray-900">{{ post.pet.description }}</dd>
              </div>
            </div>
          </div>
        </div>

        <!-- 走失信息 -->
        <div class="bg-white rounded-lg shadow p-6">
          <h2 class="text-lg font-medium text-gray-900 mb-4">{{ $t('post.lostInfo') }}</h2>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <dt class="text-sm font-medium text-gray-500">{{ $t('post.fields.lostDate') }}</dt>
              <dd class="mt-1 text-sm text-gray-900">{{ formatDate(post.last_seen_time) }}</dd>
            </div>
            <div>
              <dt class="text-sm font-medium text-gray-500">{{ $t('post.fields.location') }}</dt>
              <dd class="mt-1 text-sm text-gray-900">{{ post.last_seen_location }}</dd>
            </div>
            <div v-if="post.contact_info">
              <dt class="text-sm font-medium text-gray-500">{{ $t('post.fields.contactInfo') }}</dt>
              <dd class="mt-1 text-sm text-gray-900">{{ post.contact_info }}</dd>
            </div>
            <div>
              <dt class="text-sm font-medium text-gray-500">{{ $t('post.publisher') }}</dt>
              <dd class="mt-1 text-sm text-gray-900">{{ post.owner?.username }}</dd>
            </div>
          </div>

          <!-- 视频链接 -->
          <div v-if="post.video_url" class="mt-6">
            <dt class="text-sm font-medium text-gray-500 mb-2">{{ $t('post.relatedVideo') }}</dt>
            <a
              :href="post.video_url"
              target="_blank"
              rel="noopener noreferrer"
              class="text-primary-600 hover:text-primary-500 text-sm"
            >
              {{ $t('post.watchVideo') }} →
            </a>
          </div>
        </div>

        <!-- 行动按钮 -->
        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex flex-col sm:flex-row gap-4">
            <!-- 提供线索按钮 -->
            <button
              v-if="post.post_status === 'searching'"
              @click="showSightingForm = true"
              class="flex-1 bg-primary-600 hover:bg-primary-700 text-white px-6 py-3 rounded-lg font-medium text-center"
            >
              {{ $t('post.shareSighting') }}
            </button>



            <!-- 分享按钮 -->
            <button
              @click="showShareModal = true"
              class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-900 px-6 py-3 rounded-lg font-medium"
            >
              {{ $t('post.shareToHelp') }}
            </button>
          </div>

          <!-- 分享提示 -->
          <p class="mt-4 text-sm text-gray-600 text-center">
            {{ $t('post.shareHelpText') }}
          </p>
        </div>

        <!-- 成功提示 -->
        <div v-if="showSuccessMessage" class="rounded-md bg-green-50 p-4">
          <div class="flex">
            <div class="flex-shrink-0">
              <svg class="h-5 w-5 text-green-400" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
              </svg>
            </div>
            <div class="ml-3">
              <h3 class="text-sm font-medium text-green-800">
                {{ $t('sighting.submitSuccess') }}
              </h3>
              <div class="mt-2 text-sm text-green-700">
                <p>{{ $t('sighting.submitSuccessText') }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 线索列表 -->
        <div class="bg-white rounded-lg shadow p-6 mt-6">
          <h3 class="text-lg font-medium text-gray-900 mb-4">{{ $t('sighting.sightingsAndComments') }}</h3>

          <!-- 加载状态 -->
          <div v-if="sightingsLoading" class="text-center py-8">
            <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
            <p class="mt-2 text-sm text-gray-500">{{ $t('sighting.loadingClues') }}</p>
          </div>

          <!-- 线索和评论列表 -->
          <div v-else-if="sightings.length > 0" class="space-y-4">
            <div
              v-for="sighting in sightings"
              :key="sighting.id"
              :class="[
                'border rounded-lg p-4',
                isComment(sighting) ? 'border-blue-200 bg-blue-50' : 'border-gray-200'
              ]"
            >
              <div class="flex justify-between items-start mb-2">
                <div class="flex-1">
                  <div class="flex items-center gap-2">
                    <!-- 类型标识 -->
                    <span
                      v-if="isComment(sighting)"
                      class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
                    >
                      {{ $t('sighting.commentType') }}
                    </span>
                    <span
                      v-else
                      class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-orange-100 text-orange-800"
                    >
                      {{ $t('sighting.clueType') }}
                    </span>
                  </div>

                  <h4 v-if="!isComment(sighting)" class="font-medium text-gray-900 mt-1">
                    {{ sighting.sighting_location }}
                  </h4>
                  <p class="text-sm text-gray-500 mt-1">{{ formatDate(sighting.sighting_time) }}</p>
                </div>
                <span
                  v-if="sighting.is_verified"
                  class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800"
                >
                  {{ $t('sighting.confirmedStatus') }}
                </span>
              </div>

              <p v-if="sighting.description" class="text-sm text-gray-700 mb-3">
                {{ sighting.description }}
              </p>

              <div v-if="sighting.sighting_photo_url" class="mb-3">
                <img
                  :src="getFullImageUrl(sighting.sighting_photo_url)"
                  :alt="isComment(sighting) ? $t('sighting.commentImage') : $t('sighting.sightingImage')"
                  class="max-w-xs rounded-lg"
                  @error="(e) => (e.target as HTMLImageElement).style.display='none'"
                />
              </div>

              <p class="text-xs text-gray-400">
                {{ $t('sighting.submittedTime', { time: formatDate(sighting.created_at) }) }}
              </p>
            </div>

            <!-- 分页 -->
            <div v-if="sightingsPagination.totalPages > 1" class="flex justify-center mt-6">
              <nav class="flex items-center space-x-2">
                <button
                  @click="loadSightings(sightingsPagination.currentPage - 1)"
                  :disabled="!sightingsPagination.hasPrevPage"
                  class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {{ $t('sighting.previousPage') }}
                </button>

                <span class="px-3 py-2 text-sm text-gray-700">
                  {{ $t('sighting.pageInfo', { current: sightingsPagination.currentPage, total: sightingsPagination.totalPages }) }}
                </span>

                <button
                  @click="loadSightings(sightingsPagination.currentPage + 1)"
                  :disabled="!sightingsPagination.hasNextPage"
                  class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {{ $t('sighting.nextPage') }}
                </button>
              </nav>
            </div>
          </div>

          <!-- 无线索状态 -->
          <div v-else class="text-center py-8">
            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6-4h6m2 5.291A7.962 7.962 0 0112 15c-2.34 0-4.5-.9-6.1-2.3" />
            </svg>
            <h3 class="mt-2 text-sm font-medium text-gray-900">{{ $t('sighting.noSightingsAndComments') }}</h3>
            <p class="mt-1 text-sm text-gray-500">
              {{ $t('sighting.noSightingsAndCommentsDescription') }}
            </p>
          </div>

          <!-- 评论表单 -->
          <div class="mt-6 border-t pt-6">
            <h4 class="text-md font-medium text-gray-900 mb-4">{{ $t('sighting.postComment') }}</h4>

            <form @submit.prevent="submitComment" class="space-y-4">
              <div>
                <label for="comment-content" class="block text-sm font-medium text-gray-700 mb-2">
                  {{ $t('sighting.commentContent') }}
                </label>
                <textarea
                  id="comment-content"
                  v-model="commentForm.content"
                  rows="3"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  :placeholder="$t('sighting.commentPlaceholder')"
                  required
                ></textarea>
              </div>

              <div class="flex items-center justify-between">
                <div class="text-sm text-gray-500">
                  {{ $t('sighting.anonymousComment') }}
                </div>
                <button
                  type="submit"
                  :disabled="commentSubmitting || !commentForm.content.trim()"
                  class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <span v-if="commentSubmitting">{{ $t('sighting.submittingComment') }}</span>
                  <span v-else>{{ $t('sighting.postCommentAction') }}</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- 错误状态 -->
      <div v-else class="text-center py-12">
        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 12h6m-6-4h6m2 5.291A7.962 7.962 0 0112 15c-2.34 0-4.5-.9-6.1-2.3" />
        </svg>
        <h3 class="mt-2 text-sm font-medium text-gray-900">{{ $t('error.postNotFound') }}</h3>
        <p class="mt-1 text-sm text-gray-500">
          {{ $t('error.postNotFoundDescription') }}
        </p>
        <div class="mt-6">
          <router-link
            to="/posts"
            class="btn-primary"
          >
            {{ $t('error.backToList') }}
          </router-link>
        </div>
      </div>
    </div>

    <!-- 线索提交表单 -->
    <SightingForm
      v-if="showSightingForm && post"
      :post="post"
      @close="showSightingForm = false"
      @success="handleSightingSuccess"
    />

    <!-- 分享模态框 -->
    <ShareModal
      v-if="showShareModal && post"
      :post="post"
      @close="showShareModal = false"
    />

    <!-- 图片查看模态框 -->
    <div
      v-if="showImageModal && post?.pet?.photo_url"
      class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-75"
      @click="showImageModal = false"
    >
      <div class="relative max-w-4xl max-h-full p-4">
        <img
          :src="getFullImageUrl(post.pet.photo_url)"
          :alt="post.pet.name"
          class="max-w-full max-h-full object-contain rounded-lg"
          @click.stop
        />
        <button
          @click="showImageModal = false"
          class="absolute top-2 right-2 text-white bg-black bg-opacity-50 rounded-full p-2 hover:bg-opacity-75 transition-opacity"
        >
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { postService } from '@/services/posts'
import { sightingService } from '@/services/sightings'
import SightingForm from '@/components/SightingForm.vue'

import ShareModal from '@/components/ShareModal.vue'
import { formatDate, getFullImageUrl } from '@/utils/helpers'
import type { Post, Sighting } from '@/types'
import { POST_STATUS_LABELS } from '@/constants'
import { usePetGenderOptions } from '@/utils/i18n-options'
const route = useRoute()
const { t } = useI18n()

// 状态
const loading = ref(false)
const post = ref<Post | null>(null)
const showSightingForm = ref(false)

const showShareModal = ref(false)
const showSuccessMessage = ref(false)
const showImageModal = ref(false)

// 线索相关状态
const sightings = ref<Sighting[]>([])
const sightingsLoading = ref(false)
const sightingsPagination = ref({
  currentPage: 1,
  totalPages: 0,
  totalItems: 0,
  itemsPerPage: 10,
  hasNextPage: false,
  hasPrevPage: false
})

// 评论表单状态
const commentForm = ref({
  content: ''
})
const commentSubmitting = ref(false)

// 国际化选项
const petGenderOptions = computed(() => usePetGenderOptions())



// 工具函数
const getGenderLabel = (gender?: string) => {
  const genderOption = petGenderOptions.value.find(g => g.value === gender)
  return genderOption?.label || gender || ''
}

// 方法
const loadPost = async () => {
  try {
    loading.value = true
    const postId = parseInt(route.params.id as string)

    const response = await postService.getById(postId)

    if (response.success && response.data) {
      post.value = response.data
      // 加载帖子成功后，加载线索
      await loadSightings()
    }
  } catch (error) {
    console.error('加载帖子失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载线索列表
const loadSightings = async (page: number = 1) => {
  if (!post.value) return

  try {
    sightingsLoading.value = true

    const response = await sightingService.getPostSightingsPublic(post.value.id, {
      page,
      limit: sightingsPagination.value.itemsPerPage
    })

    if (response.success && response.data) {
      sightings.value = response.data
      if (response.pagination) {
        sightingsPagination.value = response.pagination
      }
    }
  } catch (error) {
    console.error('加载线索失败:', error)
  } finally {
    sightingsLoading.value = false
  }
}

// 判断是否为评论
const isComment = (sighting: Sighting) => {
  return sighting.sighting_location && sighting.sighting_location.startsWith('COMMENT:')
}

// 提交评论
const submitComment = async () => {
  if (!post.value || !commentForm.value.content.trim()) return

  try {
    commentSubmitting.value = true

    const commentData = {
      post_id: post.value.id,
      sighting_location: `COMMENT:${t('sighting.commentType')}`,
      sighting_time: new Date().toISOString(),
      description: commentForm.value.content.trim()
    }

    const response = await sightingService.submit(commentData)

    if (response.success) {
      // 清空表单
      commentForm.value.content = ''
      // 重新加载线索列表
      await loadSightings()
      // 显示成功消息
      showSuccessMessage.value = true
      setTimeout(() => {
        showSuccessMessage.value = false
      }, 3000)
    }
  } catch (error) {
    console.error('提交评论失败:', error)
    alert(t('sighting.commentSubmitFailed'))
  } finally {
    commentSubmitting.value = false
  }
}



const handleSightingSuccess = () => {
  showSuccessMessage.value = true
  setTimeout(() => {
    showSuccessMessage.value = false
  }, 5000)
}

onMounted(() => {
  loadPost()
})
</script>
